import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';

/** 跟时间对比 */
export function dateValidator(strDate: string): ValidatorFn {
      return (control: AbstractControl): { [key: string]: any } => {

            let forbidden: boolean;
            let controlDate: string = control.value; //当前时间
            let validatorDate = strDate.split('::'); //需要校验的时间

            //格式化时间
            let cd = new Date(controlDate);
            let vd = new Date(validatorDate[1]);

            if (validatorDate[0] == 'startDate') {
                  
                  // 跟结束时间对比
                  if (controlDate != "" && validatorDate[1] != "" && cd < vd) {
                        forbidden = true;
                  } else {
                        forbidden = false;
                  }
            }

            if (validatorDate[0] == 'endDate') {

                  // 跟开始时间对比
                  if (controlDate != "" && validatorDate[1] != "" && cd > vd) {
                        forbidden = true;
                  } else {
                        forbidden = false;
                  }

            }
            return forbidden ? { 'dateValidator': { value: control.value } } : null;

      };
}

@Directive({
      selector: '[dateValidator]',
      providers: [{ provide: NG_VALIDATORS, useExisting: DateValidatorDirective, multi: true }]
})
export class DateValidatorDirective implements Validator {

      @Input() dateValidator: string;  //时间

      validate(control: AbstractControl): { [key: string]: any } {            
            return this.dateValidator ? dateValidator(this.dateValidator)(control) : null;
      }
}

